﻿#region License

// Droid Manager - An Android Phone Tools Suite
// Copyright (C) 2011
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Ionic.Zip;
using Managed.Adb;
using DroidManager.Plugins.API;
using DroidManager.Android.Aapt;
using DroidManager.Log;
using DroidManager.Data;

namespace ApkInstaller
{
    public partial class Installer : Form
    {
        private Device _device;
        private string _apkfile;
        private AaptBrandingCommandResult _apkobj;
        private AaptHandler _ah;
        private Logger _log;
        private Thread _t;

        private string _alternateInstall;

        private string _iconExtractPath = Path.GetTempPath() + @"\ApkInstaller\";

        private delegate void CloseForm();

        private CloseForm cf;


        public Installer(Device device, string apkfile, string alternateInstall)
        {
            InitializeComponent();
            this.Shown += new EventHandler(Installer_Shown);
            _alternateInstall = alternateInstall;
            _log = Api.Logger;
            _device = device;
            _apkfile = apkfile;
            _ah = Api.AaaptHandler;
            cf = new CloseForm(Close);
            LoadInfo();
        }

        private void Installer_Shown(object sender, EventArgs e)
        {
            this.TopMost = true;
            this.TopMost = false;
        }

        private void LoadInfo()
        {
            try
            {
                AaptBrandingCommandResult apkinfo = _ah.GetLocalApkInformation(_apkfile);
                List<string> apkperm = _ah.GetLocalApkPermissions(_apkfile);
                _apkobj = apkinfo;
                appVersionLbl.Text = apkinfo.Version;
                appNameLbl.Text = apkinfo.Label;
                if (appNameLbl.Text.Length > 14)
                {
                    appNameLbl.Text = appNameLbl.Text.Replace(appNameLbl.Text.Substring(14), "...");
                }
                appPackageLbl.Text = apkinfo.Package;
                if (appPackageLbl.Text.Length > 33)
                {
                    appPackageLbl.Text = appPackageLbl.Text.Replace(appPackageLbl.Text.Substring(33), "...");
                }
                foreach (string permission in apkperm)
                {
                    permissionsTxtBox.Text += permission + Environment.NewLine;
                }

                using (ZipFile zip1 = ZipFile.Read(_apkfile))
                {
                    zip1[apkinfo.Icon].Extract(_iconExtractPath, ExtractExistingFileAction.OverwriteSilently);
                    appIconPicBox.BackgroundImage = Image.FromFile(_iconExtractPath + apkinfo.Icon);
                }
            }
            catch (Exception e)
            {
                _log.Error("Apk Installer: " + e.ToString());
                MessageBox.Show("Cannot load apk info.", "Error | Apk Installer - Droid Manager", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                this.Close();
            }
        }

        private void cancelBtn_Click(object sender, System.EventArgs e)
        {
            Close();
        }

        private void installBtn_Click(object sender, System.EventArgs e)
        {
            if (_alternateInstall == "0")
            {
                _t = new Thread(InstallApp);
                _t.Name = "Application Install";
                installProgress.Visible = true;
                installBtn.Enabled = false;
                uninstallBtn.Enabled = false;
                cancelBtn.Enabled = false;
                _t.Start();
            }
            else
            {
                Process.Start(Api.AdbPath, "-s " + _device.SerialNumber + " install -r " + _apkfile);
                Close();
            }
        }

        private void uninstallBtn_Click(object sender, EventArgs e)
        {
            _t = new Thread(UninstallApp);
            _t.Name = "Application Uninstall";
            installProgress.Visible = true;
            installBtn.Enabled = false;
            uninstallBtn.Enabled = false;
            cancelBtn.Enabled = false;
            _t.Start();
        }

        private void UninstallApp()
        {
            try
            {
                _device.UninstallPackage(_apkobj.Package);
                MessageBox.Show(_apkobj.Label + " succesfully uninstalled!", "Apk Installer - Droid Manager",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                this.Invoke(cf);
            }
            catch (Exception e)
            {
                _log.Error("Apk Installer: Error while uninstalling " + _apkobj.Package + "; " + e.ToString());
                MessageBox.Show("Error while uninstalling " + _apkobj.Package, "Error | Apk Installer - Droid Manager",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Invoke(cf);
            }
        }


        private void InstallApp()
        {
            try
            {
                _device.InstallPackage(_apkfile, true);
                MessageBox.Show("Installation Complete!", "Apk Installer - Droid Manager", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                this.Invoke(cf);
            }
            catch (Exception e)
            {
                _log.Error("Apk Installer: Error while installing " + _apkobj.Package + "; " + e.ToString());
                MessageBox.Show("Error while installing " + _apkobj.Label, "Error | Apk Installer - Droid Manager",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Invoke(cf);
            }
        }
    }
}